/**
 * elancom Corporation copy right 2012 - 2015  
 *   
 * $Header: https://192.168.1.224/svn/elancom/product/elancom-platform/trunk/src/main/java/com/elancom/framework/commons/json/util/ASMClassLoader.java 1034 2012-07-02 03:09:12Z lanzhouxue $
 * $Id: ASMClassLoader.java 1034 2012-07-02 03:09:12Z lanzhouxue $
 * $Author: lanzhouxue $
 * $Date: 2012-07-02 11:09:12 +0800 (Mon, 02 Jul 2012) $
 * $Revision: 1034 $
 */
package com.elancom.framework.commons.json.util;

import java.security.PrivilegedAction;

import com.elancom.framework.commons.json.JSONException;

public class ASMClassLoader extends ClassLoader {

	private static java.security.ProtectionDomain DOMAIN;

	static {
		DOMAIN = (java.security.ProtectionDomain) java.security.AccessController.doPrivileged(new PrivilegedAction<Object>() {

			@Override
			public Object run() {
				return ASMClassLoader.class.getProtectionDomain();
			}
		});
	}

	public ASMClassLoader() {
		super(Thread.currentThread().getContextClassLoader());
	}

	public Class<?> defineClassPublic(String name, byte[] b, int off, int len) throws ClassFormatError {
		final Class<?> clazz = defineClass(name, b, off, len, DOMAIN);

		return clazz;
	}

	public static Class<?> forName(String className) {
		try {
			final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
			return classLoader.loadClass(className);
		} catch (final ClassNotFoundException e) {
			throw new JSONException("class nout found : " + className);
		}
	}

	public static boolean isExternalClass(Class<?> clazz) {
		final ClassLoader classLoader = clazz.getClassLoader();

		if (classLoader == null) {
			return false;
		}

		ClassLoader current = Thread.currentThread().getContextClassLoader();
		while (current != null) {
			if (current == classLoader) {
				return false;
			}

			current = current.getParent();
		}

		return true;
	}
}
